<template>
  <div style="width: 100%">
    <header class="header-box">
      {{ msgType[wecomType] }}[
      <span v-if="wecomType == 3">{{ wecomItem.name }}</span>
      <span v-else>{{ wecomItem.nickname }}</span>
      ]的会话记录</header
    >
    <div class="clue-box flex justify-between">
      <div
        :class="msgList.length ? 'w-30%' : 'w-40%'"
        class="white-bgc"
        style="border-right: 1px solid #ebecf0"
      >
        <div class="customer-box" v-if="wecomType == 2">
          <el-tabs v-model="activeName" @tab-click="selectType">
            <el-tab-pane label="客户列表"> </el-tab-pane>
            <el-tab-pane label="群列表"> </el-tab-pane>
          </el-tabs>
        </div>
        <div class="header-boxs">
          <div class="header-span" :class="wecomType == 2 ? 'customer-mt' : ''">
            <span class="text-14px fw-700" v-if="wecomType == 3" style="width: 60px">群成员</span>
            <div class="search-title">
              <el-input v-model="searchValue" placeholder="请输入名称" style="padding: 0">
                <template #suffix>
                  <el-button :icon="Search" @click="inputSearch"></el-button>
                </template>
              </el-input>
            </div>
          </div>
          <div class="a-btn" v-if="wecomType == 2">
            <div
              class="btns"
              :class="item.value == timeNum ? 'active-search' : ''"
              v-for="item in searchTime"
              :key="item.id"
              @click="filerTime(item.value)"
              >{{ item.title }}</div
            >
          </div>
        </div>
        <div :class="wecomType == 2 ? 'user-list' : 'user-list2'">
          <div class="chat-view" ref="containerRef">
            <div
              class="chat-item"
              v-for="(item, key) in listMap"
              :key="key"
              :class="item.id === changeUser ? 'active' : ''"
              @click="selectItem(item, key)"
            >
              <div style="display: flex; align-items: center; width: 100%">
                <div class="chat-img">
                  <canvas
                    :key="mathRodom"
                    :ref="(el) => getDivDom(el, item)"
                    :style="{ background: ColorMap[key % 4] }"
                  ></canvas>
                </div>
                <div class="chat-name">
                  <div class="content-txt">
                    {{ item.name }}
                  </div>
                </div>
                <span :class="userTypeMap[item.userType]">
                  {{ item.type == 1 ? userTypeList[item.userType] : userTypeList2[item.userType] }}
                </span>
              </div>
              <div class="chat-time">
                <div>{{ formatDate(item.lastChatTime) }}</div>
              </div>
            </div>
          </div>
          <Pagination
            v-if="wecomType == 2"
            layout="total,prev, pager,next"
            style="margin: 5px"
            :total="totals"
            :page="params.pageNo"
            :pager-count="3"
            :limit="params.pageSize"
            @pagination="getList"
          />
        </div>
      </div>
      <div
        class="white-bgc"
        :class="msgList.length ? 'w-48%' : 'w-60%'"
        style="position: relative; border-right: 1px solid #ebecf0"
        v-loading="antiShake"
      >
        <div class="header-search">
          <div class="r-search">聊天内容</div>
          <div class="r-button">
            <div class="s-btn">
              <div
                class="btns"
                :class="selectSearch == item.id ? 'active-search' : ''"
                v-for="item in searchType"
                :key="item.id"
                @click="selectSearchItem(item.id, item.value)"
                >{{ item.title }}</div
              >
            </div>
            <div style="width: 300px; text-align: right">
              <el-date-picker
                v-model="sendTime"
                @change="searchPicker"
                value-format="YYYY-MM-DD HH:mm:ss"
                type="daterange"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                class="!w-240px"
              />
            </div>
          </div>
        </div>
        <div class="login-box" v-if="!isLogin">
          <wxLogin @setIsLogin="setIsLogin" @success="createdComponentDisplay" />
        </div>
        <div id="wechatbox" ref="wechatbox"></div>
      </div>
      <div class="w-22% group-box" v-if="msgList.length">
        <GroupAnalysis v-if="wecomType == 3" :wecomItem="wecomItem" @setMsgList="setMsgList" />
        <template v-if="activeName == '0'">
          <CustomerAnalysis
            v-if="wecomType == 2 && externalUserId"
            :wecomItem="wecomItem"
            :externalUserId="externalUserId"
          />
        </template>
        <template v-if="activeName == '1'">
          <GroupAnalysis
            v-if="wecomType == 2 && listSelectValue"
            :wecomItem="wecomItem"
            @setMsgList="setMsgList"
          />
        </template>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { formatDate } from '@/utils/formatTime'
import * as WeComApiConfigApi from '@/api/wecom/apiconfig'
import * as ww from '@wecom/jssdk'
const divDomList = ref(new Map())
import wxLogin from '../../user/components/wxLogin.vue'
import weComConfig from '@/utils/weComConfig'
import { getByChatMsgList } from '@/api/wecom/user/index'
import { Search } from '@element-plus/icons-vue'
import { createSummaryTask } from '@/api/wecom/sessionAudit/index'
import GroupAnalysis from './groupAnalysis.vue'
import CustomerAnalysis from './customerAnalysis.vue'
import log from '@/utils/log'

/*防抖*/
const antiShake = ref(false)
const ColorMap = ref([
  'rgb(132, 202, 176)',
  'rgb(188, 158, 221)',
  'rgb(125, 179, 217)',
  'rgb(140, 163, 205)'
])
const props = defineProps({
  listMap: Array,
  wecomItem: Object,
  wecomType: String,
  params: Object,
  totals: Number
})
const { params, totals } = toRefs(props)
const timeNum = ref(-1)
const msgType = {
  1: '客户',
  2: '员工',
  3: '群'
}
const userTypeMap = {
  0: 'greyMsg',
  1: 'warnMsg',
  2: 'errorMsg'
}
// type = 1
const userTypeList = {
  0: '企业员工',
  1: '管理员',
  2: '群主'
}
// type = 2
const userTypeList2 = {
  0: '外部联系人',
  1: '管理员',
  2: '群主'
}
const { listMap, wecomItem, wecomType } = toRefs(props)
const searchValue = ref(null)
const searchType = ref([
  {
    title: '全部',
    value: '',
    id: 0
  },
  {
    title: '文件',
    value: '8',
    id: 1
  },
  {
    title: '图片',
    value: '2',
    id: 2
  },
  {
    title: '语音',
    value: '6',
    id: 3
  },
  {
    title: '语音通话',
    value: '22',
    id: 4
  }
])
const searchTime = ref([
  {
    title: '今日会话',
    value: 0,
    id: 0
  },
  {
    title: '昨日会话',
    value: 1,
    id: 1
  },
  {
    title: '最近七日会话',
    value: 2,
    id: 2
  },
  {
    title: '重置',
    value: 3,
    id: 3
  }
])
const selectSearch = ref(0)
const selectValue = ref('')
const sendTime = ref('')
const activeName = ref('0')

const emit = defineEmits([
  'searchFilter',
  'setPage',
  'setFilterTime',
  'employeeGroupList',
  'setWidth'
])
const inputSearch = () => {
  emit('searchFilter', searchValue.value, activeName.value)
}

/*过滤时间*/
const filerTime = (num) => {
  timeNum.value = num
  emit('setFilterTime', num, activeName.value)
}

// 列表分页
const getList = (val) => {
  emit('setPage', val, activeName.value)
}

//切换群还是组
const selectType = (tab, event) => {
  if (tab.index == 0) {
    emit('setPage', 1, 0)
  } else {
    emit('employeeGroupList', 1)
  }
  activeName.value = tab.index
  listSelectValue.value = null
  limit.value.pageNo = 1
  noMore.value = false
  changeUser.value = ''
  msgList.value = []
}
watch(
  () => divDomList.value,
  (value) => {
    listMap.value.forEach((item) => {
      const canvas = value.get(item.id)
      if (canvas) {
        let companyName
        if (wecomType.value == 1) {
          companyName = item.userNickname ? item.userNickname.slice(0, 2).toUpperCase() : ''
        } else if (wecomType.value == 2 || wecomType.value == 3) {
          companyName = item.name ? item.name.slice(0, 2).toUpperCase() : ''
        }
        let positLeft = 50
        const ctx = canvas.getContext('2d')
        ctx.scale(1, 0.5)
        ctx.font = '100px sans-serif'
        ctx.fillStyle = '#fff'
        ctx.fillText(companyName, positLeft, 180)
      }
    })
  },
  { immediate: true, deep: true }
)
const mathRodom = ref(0)
watch(
  () => listMap.value,
  (val) => {
    if (val?.length) {
      mathRodom.value++
    }
  },
  { immediate: true, deep: true }
)
const getDivDom = (el, item) => {
  if (el) {
    divDomList.value.set(item.id, el)
  }
}
const toDate = (number) => {
  var date = new Date(number)
  var Y = date.getFullYear() + '-'
  var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'
  var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate()

  // 添加时分秒
  var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
  var Min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()
  var S = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds()

  return Y + M + D + ' ' + H + ':' + Min + ':' + S
}
const formData = ref(null)
const jsapiSignature = ref(null)
// 初始化
onBeforeMount(() => {
  getWeComApiConfig()
})
const getWeComApiConfig = async () => {
  try {
    formData.value = await WeComApiConfigApi.getWeComApiConfig()
    jsapiSignature.value = await WeComApiConfigApi.getJsapiSignature({
      url: window.location.href
    })
    initComponentSession()
  } finally {
  }
}
const initComponentSession = async () => {
  try {
    ww.register({
      corpId: formData.value.corpId,
      agentId: formData.value.agentId,
      jsApiList: ['selectExternalContact', 'shareAppMessage', 'wwapp.invokeJsApiByCallInfo'],
      getAgentConfigSignature
    })
  } catch {}
  // 会话组件需要确保 WWOpenData 初始化成功
  await ww.initOpenData()
}
const getAgentConfigSignature = async () => {
  return ww.getSignature(jsapiSignature.value.jsapiTicket)
}
const factory = ww.createOpenDataFrameFactory()
const wechatbox = ref(null)
const changeUser = ref('')
const externalUserId = ref('')
const msgList = ref([])
const isLogin = ref(true)
const listSelectValue = ref()

const limit = ref({
  pageNo: 1,
  pageSize: 10
})
const noMore = ref(false)
const qwUserId = ref(null)
// 点击详情
const selectItem = (item, key) => {
  if (antiShake.value || wecomType.value == 3) return
  listSelectValue.value = item
  limit.value.pageNo = 1
  noMore.value = false
  msgList.value = []
  if (wecomType.value == 2) {
    // 客户
    if (activeName.value == '0') {
      externalUserId.value = item.externalUserId
      antiShake.value = true
      messageSentimentAnalysis.value = []
      getMsgRecordPage()
      changeUser.value = item.id
    } else {
      antiShake.value = true
      msgList.value = []
      messageSentimentAnalysis.value = []
      changeUser.value = item.id
      getGroupMsg()
      // 群
      log.error('群', JSON.stringify(item))
    }
  }
}
const sentiment_result_map = {
  '0': '中性情绪',
  '1': '正面情绪',
  '2': '负面情绪'
}
// 情感分析数据
const messageSentimentAnalysis = ref([])
// 消息情感分析
const setMsgList = (val) => {
  messageSentimentAnalysis.value = val
  msgList.value = msgList.value.map((item) => {
    const match = val.find((a) => a.msgid === item.msgid)
    return {
      ...item,
      sentiment_result: match ? sentiment_result_map[match.sentiment_result] : undefined
    }
  })
  // log.error('消息列表:', JSON.stringify(msgList.value))
  // log.success('消息情感分析结果', JSON.stringify(val))
}
// 群消息
const getGroupMsg = async () => {
  if (noMore.value) return
  const { list } = await getByChatMsgList({
    weChatId: wecomItem.value.chatId,
    msgtype: selectValue.value,
    sendTime: sendTime.value,
    pageNo: limit.value.pageNo,
    pageSize: limit.value.pageSize
  })
  if (list.length == 0) {
    noMore.value = true
  }
  list.forEach((element) => {
    let sendName = listMap.value?.find((item) => item.weUserId == element.senderId)
    element.weComeName = sendName ? sendName.name : '系统'
    element.sendTime = toDate(element.sendTime)
  })
  list.map((item) => {
    msgList.value.unshift(item)
  })
  if (messageSentimentAnalysis.value.length) {
    setMsgList(messageSentimentAnalysis.value)
  }
  if (instance.value) {
    instance.value.setData({
      list: msgList.value
    })
    antiShake.value = false
  } else {
    createdComponentDisplay()
  }
}
watch(
  () => wecomType.value,
  (value) => {
    if (value == 3) {
      antiShake.value = true
      limit.value.pageNo = 1
      noMore.value = false
      msgList.value = []
      messageSentimentAnalysis.value = []
      getGroupMsg()
    }
  },
  { immediate: true, deep: true }
)

// 是否登录
const setIsLogin = (val) => {
  isLogin.value = val
  if (val) antiShake.value = false
}
const searchPicker = () => {
  limit.value.pageNo = 1
  noMore.value = false
  msgList.value = []
  if (wecomType.value == 1 || wecomType.value == 2) {
    getMsgRecordPage(qwUserId.value)
  } else {
    getGroupMsg()
  }
}
// 筛选消息类型
const selectSearchItem = (id, val) => {
  if (wecomType.value == 1 || wecomType.value == 2) {
    if (!externalUserId.value) {
      return
    }
    selectSearch.value = id
    selectValue.value = val
    limit.value.pageNo = 1
    noMore.value = false
    msgList.value = []
    getMsgRecordPage()
  } else {
    selectSearch.value = id
    selectValue.value = val
    limit.value.pageNo = 1
    noMore.value = false
    msgList.value = []
    getGroupMsg()
  }
}
const instance = ref(null)
// 获取客户跟进人列表 会话详情
const getMsgRecordPage = async (qwUserId) => {
  if (noMore.value) return
  const { list } = await WeComApiConfigApi.listByCustomer({
    weCustomerId: externalUserId.value,
    weUserId: qwUserId ? qwUserId : wecomItem.value.weUserId,
    msgtype: selectValue.value,
    sendTime: sendTime.value,
    pageNo: limit.value.pageNo,
    pageSize: limit.value.pageSize
  })
  if (list.length == 0) {
    noMore.value = true
    if (instance.value) {
      instance.value.setData({
        moreData: true
      })
    }
  } else {
    if (instance.value) {
      instance.value.setData({
        moreData: false
      })
    }
  }
  list.forEach((element) => {
    element.sendTime = toDate(element.sendTime)
    if (wecomType.value == 1) {
      let sendName = listMap.value.find((item) => item.qwUserId == element.senderId)
      let sendName2 = [wecomItem.value].find((item) => item.externalUserId == element.senderId)
      element.weComeName = sendName ? sendName.userNickname : sendName2.name
    } else {
      let sendName = listMap.value.find((item) => item.externalUserId == element.weUserId)
      let sendName2 = [wecomItem.value].find((item) => item.weUserId == element.weUserId)
      element.weComeName = sendName ? sendName.name : sendName2.nickname
    }
  })
  list.map((item) => {
    msgList.value.unshift(item)
  })
  if (messageSentimentAnalysis.value.length) {
    setMsgList(messageSentimentAnalysis.value)
  }
  if (instance.value) {
    instance.value.setData({
      list: msgList.value
    })
    antiShake.value = false
  } else {
    createdComponentDisplay()
  }
}
const createdComponentDisplay = () => {
  if (sessionStorage.getItem('weComCode')) {
  } else {
    console.log('企业微信没有登录')
    antiShake.value = false
    setIsLogin(false)
    return
  }
  if (wechatbox.value) {
    wechatbox.value.innerHTML = '' // 清空容器
  }
  instance.value = factory.createOpenDataFrame({
    el: wechatbox.value, // “容器”元素，用于挂载展示组件
    template: `
    <scroll-view scroll-y="{{true}}" scroll-top="{{data.scrollTop}}" bindscrolltoupper="scrolltoupper" upper-threshold="{{data.threshold}}" class="scrollCompany">
      <view class="msgTitle" wx:if="{{data.moreData || data.list.length==0}}">没有更多消息了...</view>
      <view
        wx:for="{{data.list}}"
        wx:key="msgid"
        class="msg {{item.senderType==1||item.senderType==3?'flexEnd':'flexStart'}}"
        data-index="{{index}}"
        >
        <view class="txtFont" wx:if="{{item.sentiment_result}}">{{item.sentiment_result}}</view>
        <view class="txtFont">[{{item.weComeName}}] {{item.sendTime}}</view>
        <ww-open-message
          class="custom-open-message {{item.senderType==1||item.senderType==3?'activeRight':'activeLeft'}}"
          message-id="{{item.msgid}}"
          secret-key="{{item.secureKey}}"
          open-type="viewMessage"
        />
     </view>
    </scroll-view>
  `,
    style: `
    .scrollCompany{
      height:100%;
    }
    .msg {
      padding:10px;
      padding-top: 20px;
      display:flex;
      flex-direction:column;
    }
    .flexEnd{
      align-items:flex-end;
    }
    .flexStart{
      align-items:flex-start;
    }
    .txtFont{
      font-size:12px;
      margin-bottom:6px;
      color:#494a4d;
    }
    .msgTitle{
      text-align:center;
      font-size:14px;
      padding:10px 0;
      color:burlywood;
    }
    .custom-open-message{
      padding-top: 20px;
      padding: 10px;
      border-radius: 4px;
    }
    .activeRight{
       background: #b3d4ff;
       display: inline-block;
    }
    .activeLeft{
      background: #ebecf0;
      display: inline-block;
    }
  `,
    error: (err) => {
      if (err.errMsg == 'Missing open sid') {
        setIsLogin(false)
      }
    },
    handleMounted: (val) => {
      console.log('视图挂载成功后的回调', val)
    },
    data: {
      list: msgList.value,
      threshold: 20,
      scrollTop: 200,
      moreData: false
    },
    methods: {
      scrolltoupper() {
        limit.value.pageNo += 1
        if (wecomType.value == 1) {
          getMsgRecordPage(listSelectValue.value.qwUserId)
        } else {
          getMsgRecordPage()
        }
      }
    }
  })
}
watch(
  () => instance.value,
  (val) => {
    if (val) antiShake.value = false
  },
  { immediate: true, deep: true }
)
watch(
  () => msgList.value,
  (value) => {
    emit('setWidth', value.length == 0)
  },
  { immediate: true, deep: true }
)
</script>

<style lang="scss" scoped>
.errorMsg {
  color: #f56c6c;
  margin-left: 10px;
  font-size: 12px;
  position: absolute;
  right: 10px;
  top: 10px;
}
.greyMsg {
  color: #505f79;
  margin-left: 10px;
  font-size: 12px;
  position: absolute;
  right: 10px;
  top: 10px;
}
.warnMsg {
  color: #e6a23c;
  margin-left: 10px;
  font-size: 12px;
  position: absolute;
  right: 10px;
  top: 10px;
}
.customer-box {
  padding: 0 20px;
}
.header-boxs {
  border-bottom: 1px solid #e0e1e2;
  background: #eff3f6;
  .header-span {
    padding: 19px 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    z-index: 9;
    .search-title {
      width: 100%;
    }
  }
}
::v-deep .search-title {
  .el-input {
    .el-input__wrapper {
      padding: 1px 0 1px 11px;
    }
  }
}
.customer-mt {
  margin-top: -16px;
}
.header-box {
  background-color: #fff;
  padding: 10px;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid rgb(239, 243, 246);
}
h4 {
  margin: 0;
}
::v-deep #wechatbox {
  iframe {
    width: 100%;
    height: 100%;
    background: #f4f5f7;

    &::-webkit-scrollbar {
      width: 2px;
    }
    &::-webkit-scrollbar-track {
      background: #f1f1f1;
    }
    &::-webkit-scrollbar-thumb {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:hover {
      background: #d8d8d8;
    }
    &::-webkit-scrollbar-thumb:horizontal:start {
      border-top-left-radius: 4px;
      border-bottom-left-radius: 4px;
    }
    &::-webkit-scrollbar-thumb:horizontal:end {
      border-top-right-radius: 4px;
      border-bottom-right-radius: 4px;
    }
  }
}
canvas {
  width: 30px;
  height: 30px;
  border-radius: 4px;
}
.clue-box {
  width: 100%;
  height: 100%;
}
.white-bgc {
  background-color: #fff;
}
.left-box {
  padding: 20px;
  border-bottom: 2px solid #ebecf0;
}
.user-list {
  height: calc(100% - 180px);
}
.user-list2 {
  height: calc(100% - 80px);
}
.chat-view {
  height: calc(100% - 42px);
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  &::-webkit-scrollbar {
    width: 2px;
  }
  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }
  &::-webkit-scrollbar-thumb {
    background: #d8d8d8;
  }
  &::-webkit-scrollbar-thumb:hover {
    background: #d8d8d8;
  }
  &::-webkit-scrollbar-thumb:horizontal:start {
    border-top-left-radius: 4px;
    border-bottom-left-radius: 4px;
  }
  &::-webkit-scrollbar-thumb:horizontal:end {
    border-top-right-radius: 4px;
    border-bottom-right-radius: 4px;
  }
  .active {
    background: #d1def0;
  }
  .chat-item {
    position: relative;
    width: calc(100% - 20px);
    padding: 4px 10px;
    border-bottom: 1px solid #e0e1e2;
    display: flex;
    align-items: center;
    justify-content: space-between;
    cursor: pointer;
    .chat-img {
      position: relative;
      .el-image {
        width: 40px;
        height: 40px;
        border-radius: 50%;
      }
    }
    .chat-name {
      margin-left: 12px;
      width: 150px;
      display: flex;
      flex-direction: column;
      justify-content: space-around;
      .content-title {
        display: flex;
        .pc-name {
          font-size: 16px;
          color: #000;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          margin-right: 5px;
        }
      }
      .content-txt {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 12px;
        color: #959291;
      }
    }
    .chat-time {
      width: 166px;
      color: #959291;
      font-size: 12px;
      display: flex;
      flex-direction: column;
      justify-content: flex-end;
      align-items: flex-start;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.login-box {
  width: 100%;
  position: absolute;
  top: 72px;
  right: 0;
  z-index: 2;
  height: calc(100% - 72px);
}
#wechatbox {
  height: calc(100% - 114px);
}
.header-search {
  height: 72px;
  border-bottom: 2px solid #ebecf0;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  .r-search {
    padding: 0 20px;
  }
  .r-button {
    padding: 0 20px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .s-btn {
      display: flex;
      .btns {
        margin-right: 20px;
        padding: 4px 12px;
        font-size: 14px;
        cursor: pointer;
        background-color: #f6f6f7;
        color: #172b4d;
        font-weight: bold;
        border-radius: 4px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      .active-search {
        background-color: #505f79;
        color: #fff;
      }
    }
  }
}
.a-btn {
  display: flex;
  padding: 0 20px 10px 20px;
  margin-top: -10px;
  .btns {
    margin-right: 20px;
    padding: 4px 12px;
    font-size: 14px;
    cursor: pointer;
    background-color: #fff;
    color: #172b4d;
    font-weight: bold;
    border-radius: 4px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .active-search {
    background-color: #505f79;
    color: #fff;
  }
}
.group-box {
  background-color: #f6f6f7;
}
</style>
